<template>
  <li>
    <div class="root">
      <div class="item">
        <input type="checkbox" :checked="item.done" @change=checkedChange(item.id)>
      </div>
      <div class="item" v-show=!this.item.isEdit>
        <span>{{ item.content }}</span>
      </div>
      <div class="item" v-show=this.item.isEdit>
        <input ref="contentInput" type="text" :value=item.content @blur="cancelEdit">
      </div>
      <div class="item">
        <button @click="editItem" v-show="!this.item.isEdit">编辑</button>
      </div>
      <div class="item">
        <button @click="deleteTodo(item.id)">删除</button>
      </div>
    </div>
  </li>
</template>

<script>
import { nextTick } from 'vue';
export default {
  props: ["item", "finish"],
  data() {
    return {

    };
  },
  computed: {
    content: {
      get() {
        return this.item.content
      },
      set(v) {
        if (v.length == 0) {
          return
        }
        this.item.content = v
      }
    },
    // isEdit: {
    //   get() {
    //     console.log('isEdit被调用')
    //     if (this.item.hasOwnProperty('isEdit')) {
    //       return this.item.isEdit
    //     } else {
    //       this.$set(this.item, 'isEdit', false)
    //       return false
    //     }
    //   },
    //   set(v){
    //     this.item.isEdit = v
    //   }
    // }

  },
  methods: {

    checkedChange(id) {
      this.$bus.$emit('finishTodo', id)
    },
    deleteTodo(id) {
      this.$bus.$emit('deleteTodo', id, 1, 2, 3, 4, 5)
    },
    editItem() {
      if (this.item.hasOwnProperty('isEdit')) {
        this.item.isEdit = true
      } else {
        this.$set(this.item, 'isEdit', true)
      }
      console.log('-------------')
      this.$nextTick(() => {
        this.$refs.contentInput.focus();
      })

    },
    cancelEdit() {

      console.log("@@@")

      let content = this.$refs.contentInput.value
      if (content.length === 0) {
        
        alert("请输入要做的事")
        // this.$refs.contentInput.focus();
        // this.$refs.contentInput.focus();

        // this.$nextTick(() => {
        //   this.$refs.contentInput.focus();
        // })
        //setInterval
        setTimeout(()=>{
          console.log("+++")
          this.$refs.contentInput.focus();
        },300)

      } else {
        this.item.content = content
        this.item.isEdit = false
      }
    },
  },
};
</script>

<style lang="less" scoped>
li:hover {
  background-color: #ccc;

  // 选中li内部任意深度的子元素中的button  
  button {
    display: inline-block
  }
}

.root {
  border-bottom: 1px solid lightgrey;
  display: flex;
  flex-direction: row;
  padding-left: 10px;
  padding-right: 10px;
  justify-content: flex-start;
  align-items: center;
  height: 40px;
  gap: 10px;

  button {
    display: none;
  }

  .item:nth-last-child(2) {
    margin-left: auto;
  }
}
</style>